import { createRouter, createWebHashHistory } from "vue-router";
import routes from "@/router/routes.ts";
import { getToken } from "@/utils";
import useLayoutStore from "@/stores/modules/useLayoutStore.ts";
import Local from "@/utils/local";

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

// 不使用参数前面加_
router.beforeEach((to, _form, next) => {
    const { setTabList } = useLayoutStore()

    const defaultRoute = Local.localRead('defaultRouter')!
    const token = getToken()
    const teacherData = Local.localRead("teacher");
    const role = teacherData ? JSON.parse(teacherData) : null;

    if (token) {
        if (teacherData) {
            if (to.name === 'expertLogin') {
                next({
                    name: "expertReview"
                })
            }
            if (to.path === '/') {
                next({
                    name: "expertReview"
                })
            }
        } else {
            if (to.name === 'login') {
                next({
                    path: defaultRoute
                })

            }
            if (to.path === '/') {
                next({
                    path: defaultRoute || '/system/user'
                })
            }
            if (to.meta.isTab === 0) {
                setTabList(to.path)
            }
        }
        next()
    } else {
        console.log(to.name, "to.nameto.name");

        if (to.name !== 'login' && to.name !== 'expertLogin') {
            next({
                name: 'login',
            })
        } else {
            next()
        }
    }
})

export default router